//part1:C09:ex9.43.cpp
//a function to replace string.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void replace_string(string& str, const string &oldVal, const string& newVal) {
  auto ilen = oldVal.size();
  if (!ilen) {
    return;
  } 

  auto iter = str.begin();
  while (iter <= str.end() - 1) {
    auto iter1 = iter;
    auto iter2 = oldVal.begin();

    while (iter2 != oldVal.end() && *iter1 == *iter2) {
      iter1++;
      iter2++;
    }
    if (iter2 == oldVal.end()) {
      iter = str.erase(iter, iter1); 
      if (newVal.size()) {
        iter2 = newVal.end();
        do{
          iter2--;
          iter = str.insert(iter, *iter2);
        } while (iter2 > newVal.begin());
      }
      iter += newVal.size();
    } else {
      iter++;
    }
  }
}

int main(void) {
  string s1 = "tho thru tho!";
  replace_string(s1, "thru", "through");
  cout << s1 << endl;
  replace_string(s1, "tho", "though");
  cout << s1 << endl;

  replace_string(s1, "through", "");
  cout << s1 << endl;

  return 0;
}
